package com.hospital.hospitalauth.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.hospital.hospitalauth.entity.User;
import com.hospital.hospitalauth.mapper.UserMapper;
import com.hospital.hospitalauth.service.IUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 王晓康
 * @since 2020-10-17
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService, UserDetailsService {

    @Autowired
    IUserService itUserService;


    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        log.info("用户名：{}",s);
        Wrapper<User> tUserWrapper = new EntityWrapper<User>();
        tUserWrapper.eq("username",s);
        User tUser = itUserService.selectOne(tUserWrapper);
        if (tUser==null){
            throw  new UsernameNotFoundException("用户名不正确");
        }
        log.info(passwordEncoder.encode(tUser.getPassword()));
        User userByUsername = this.baseMapper.getUserByUsername(s);
        String name = userByUsername.getName();
        return new org.springframework.security.core.userdetails.User(s,tUser.getPassword(), AuthorityUtils.createAuthorityList(name));
    }

}
